/*eslint-disable*/
// @ts-nocheck

import { unref } from 'vue';

import {
  Cartesian3,
  Cesium3DTileset,
  CesiumTerrainProvider,
  ClassificationType,
  Color,
  PrimitiveCollection,
  Rectangle,
  Resource,
  UrlTemplateImageryProvider,
  Viewer,
  WebMapTileServiceImageryProvider,
} from '@space8/czm-plugin';
import { addWaterLayer } from '@/components/GlobalCesium/src/waterLayer';
import PolylineTrailMaterialProperty
  from '@/components/GlobalCesium/src/PolylineTrailMaterialProperty';
import { loadStation } from '@/components/GlobalCesium/src/station';

const globPathname = window.localStorage.getItem('GlobPathname');

// 地图对象
let globalViewer: Viewer;
// 河道对象集合
let waterPrimitiveCollection: PrimitiveCollection;
// 水库对象集合
let reservoirsPrimitiveCollection: PrimitiveCollection;
// 倾斜模型
let cesium3DTileset: Cesium3DTileset;

// 初始化地图
const initBasicMap = (target: any): Viewer => {
  const cesiumContainer: any = unref(target);
  const viewer = new Viewer(cesiumContainer, {
    selectionIndicator: false,
    msaaSamples: 4,
    creditContainer: null,
  });
  viewer.scene.postProcessStages.fxaa.enabled = true;
  waterPrimitiveCollection = new PrimitiveCollection();
  reservoirsPrimitiveCollection = new PrimitiveCollection();
  viewer.scene.primitives.add(waterPrimitiveCollection);
  viewer.scene.primitives.add(reservoirsPrimitiveCollection);

  // 储存地图对象
  globalViewer = viewer;

  return viewer;
};

/**
 * 加载天地图影像
 */
function addBaseImageLayers() {
  globalViewer.imageryLayers.addImageryProvider(
    new WebMapTileServiceImageryProvider({
      url: 'http://{s}.tianditu.gov.cn/img_w/wmts?style=default&format=tiles&tk=14ba77517bab8f35dcc7d88916ee09cd',
      layer: 'img',
      format: 'tiles',
      style: 'default',
      tileMatrixSetID: 'w',
      subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
    }),
  );

  globalViewer.imageryLayers.addImageryProvider(
    new WebMapTileServiceImageryProvider({
      url: 'http://{s}.tianditu.gov.cn/cia_w/wmts?style=default&format=tiles&tk=14ba77517bab8f35dcc7d88916ee09cd',
      layer: 'cia',
      format: 'tiles',
      style: 'default',
      tileMatrixSetID: 'w',
      subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
    }),
  );
}

/**
 * 添加业务图层
 */
function addBussImageLayers() {
  globalViewer.imageryLayers.addImageryProvider(
    new UrlTemplateImageryProvider({
      url: globPathname + '/xyh_gis_server/{z}/{x}/{y}.png',
      rectangle: Rectangle.fromDegrees(
        118.8367021703409421,
        32.2291993350104562,
        119.0690091029512985,
        32.4159184162296441,
      ),
      minimumLevel: 6,
      maximumLevel: 17,
    }),
  );

  globalViewer.imageryLayers.addImageryProvider(
    new UrlTemplateImageryProvider({
      url:
        globPathname +
        '/xyhgq/geoserver/gwc/service/tms/1.0.0/grkj_workspace%3Adpriver@EPSG%3A900913@png/{z}/{x}/{reverseY}.png',
      rectangle: Rectangle.fromDegrees(
        118.56620788574219,
        32.189720153808594,
        119.0816421508789,
        32.600345611572266,
      ),
      minimumLevel: 8,
      maximumLevel: 18,
    }),
  );

  // 标注
  globalViewer.imageryLayers.addImageryProvider(
    new UrlTemplateImageryProvider({
      url:
        globPathname +
        '/xyhgq/geoserver/gwc/service/tms/1.0.0/grkj_workspace%3Adpchannelline@EPSG%3A900913@png/{z}/{x}/{reverseY}.png',
      rectangle: Rectangle.fromDegrees(
        118.60253143310547,
        32.246578216552734,
        119.07060241699219,
        32.596858978271484,
      ),
      minimumLevel: 8,
      maximumLevel: 18,
    }),
  );
}

/**
 * 添加地形
 */
async function addTerrain() {
  globalViewer.terrainProvider = await CesiumTerrainProvider.fromUrl('http://data.mars3d.cn/terrain/');
}

/**
 * 添加倾斜数据
 */
async function add3DTiles() {
  cesium3DTileset = await Cesium3DTileset.fromUrl(globPathname + '/xyhgq/osgb/tileset.json', {
    maximumScreenSpaceError: 64,
    cacheBytes: 536870912 * 2,
    maximumCacheOverflowBytes: 536870912 * 2,
  });
  globalViewer.scene.primitives.add(cesium3DTileset);
}

/**
 * 添加水库动态图层
 */
function addFlowReservoirs() {
  // 水库面
  addWaterLayer(reservoirsPrimitiveCollection, 'data/shuiku.geojson');
  // 水库动态线
  Resource.fetchJson('data/shuiku.geojson').then((response) => {
    response.features.forEach((feature) => {
      const positions = feature.geometry.coordinates[0].map((t) => Cartesian3.fromDegrees(t[0], t[1]));
      globalViewer.entities.add({
        polyline: {
          positions: positions,
          width: 10,
          clampToGround: true,
          material: new PolylineTrailMaterialProperty({
            color: Color.fromCssColorString('#2b94ca'),
            speed: 10,
          }),
          classificationType: ClassificationType.BOTH,
          zIndex: 2,
        },
      });
    });
  });
}

/**
 * 添加河道动态图层
 * @param type
 */
function addFlowRiver(type: 'whole' | 'demonstration') {
  if (type === 'whole') {
    addWaterLayer(waterPrimitiveCollection, 'data/water.geojson'); // 全区河道
  } else if (type === 'demonstration') {
    addWaterLayer(waterPrimitiveCollection, 'data/water_shifanqu.geojson'); // 示范区河道
  }
}

/**
 * 添加站点图层
 */
function loadAnimateStation(type: 'all' | 'demonstrate') {
  loadStation(globalViewer, type);
}

// 返回地图对象，供调用的组件使用
const getGlobalViewer = () => {
  return globalViewer;
};

/**
 * 销毁Viewer
 */
const destroyViewer = () => {
  globalViewer.entities.removeAll();
  globalViewer.imageryLayers.removeAll();
  globalViewer.dataSources.removeAll(true);
  waterPrimitiveCollection.removeAll();
  waterPrimitiveCollection = null;
  reservoirsPrimitiveCollection.removeAll();
  reservoirsPrimitiveCollection = null;
  if (cesium3DTileset) {
    globalViewer.scene.primitives.remove(cesium3DTileset);
    cesium3DTileset = null;
  }
  globalViewer.destroy();
  globalViewer = null;
};

/**
 * 控制是否显示站点
 * @param type 站点类型
 * CZ -> 水位站
 * RR -> 水文站
 * SN -> 枢纽
 * SZ -> 水闸
 * BZ -> 泵站
 * HZ -> 涵闸
 * WQ -> 水质站
 * WSK -> 污水口
 * @param status 显示与否
 */
const showStation = (type: string, status: boolean) => {
  const dataSources = globalViewer.dataSources.getByName(type);
  if (dataSources.length > 0) {
    dataSources[0].show = status;
  }
};

/**
 * 是否显示全景点
 * @param status
 */
const showView360 = (status: boolean) => {
  globalViewer.dataSources.getByName('360')[0].show = status;
};

export {
  initBasicMap,
  getGlobalViewer,
  destroyViewer,
  showStation,
  showView360,
  addBaseImageLayers,
  addBussImageLayers,
  addTerrain,
  addFlowReservoirs,
  loadAnimateStation,
  addFlowRiver,
  add3DTiles,
};
